<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理页面</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .user-table { margin-top: 20px; }
        .action-btns .btn { margin: 2px; }
    </style>
</head>
<body>
    <div class="container mt-4">
        <!-- 操作栏 -->
        <div class="d-flex justify-content-between mb-3">
            <h3>用户管理</h3>
            <button class="btn btn-primary" onclick="showModal('create')">
                新建用户
            </button>
        </div>

        <!-- 用户列表 -->
        <table class="table table-hover user-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>用户名</th>
                    <th>邮箱</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="userList">
                <!-- 数据动态加载 -->
            </tbody>
        </table>

        <!-- 操作模态框 -->
        <div class="modal fade" id="userModal">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="modalTitle">新建用户</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form id="userForm">
                            <input type="hidden" id="userId">
                            <div class="mb-3">
                                <label class="form-label">用户名</label>
                                <input type="text" class="form-control" id="username" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">邮箱</label>
                                <input type="email" class="form-control" id="email" required>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="saveUser()">保存</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
    <script>
        // 初始化加载数据
        document.addEventListener('DOMContentLoaded', loadUsers);

        // 加载用户列表
        async function loadUsers() {
            try {
                const response = await fetch('/api/users');
                const users = await response.json();
                renderUsers(users);
            } catch (error) {
                alert('加载用户列表失败');
            }
        }

        // 渲染用户列表
        function renderUsers(users) {
            const tbody = document.getElementById('userList');
            tbody.innerHTML = users.map(user => `
                <tr>
                    <td>${user.id}</td>
                    <td>${user.username}</td>
                    <td>${user.email}</td>
                    <td class="action-btns">
                        <button class="btn btn-sm btn-warning" onclick="showModal('edit', ${user.id})">编辑</button>
                        <button class="btn btn-sm btn-danger" onclick="deleteUser(${user.id})">删除</button>
                    </td>
                </tr>
            `).join('');
        }

        // 显示模态框
        async function showModal(action, userId = null) {
            const modal = new bootstrap.Modal('#userModal');
            const form = document.getElementById('userForm');

            if (action === 'edit') {
                document.getElementById('modalTitle').textContent = '编辑用户';
                const user = await getUser(userId);
                document.getElementById('userId').value = user.id;
                document.getElementById('username').value = user.username;
                document.getElementById('email').value = user.email;
            } else {
                document.getElementById('modalTitle').textContent = '新建用户';
                form.reset();
            }
            modal.show();
        }

        // 获取单个用户
        async function getUser(userId) {
            try {
                const response = await fetch(`/api/users/${userId}`);
                return await response.json();
            } catch (error) {
                alert('获取用户信息失败');
            }
        }

        // 保存用户
        async function saveUser() {
            const user = {
                id: document.getElementById('userId').value,
                username: document.getElementById('username').value,
                email: document.getElementById('email').value
            };

            try {
                const url = user.id ? `/api/users/${user.id}` : '/api/users';
                const method = user.id ? 'PUT' : 'POST';

                const response = await fetch(url, {
                    method: method,
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(user)
                });

                if (response.ok) {
                    loadUsers();
                    bootstrap.Modal.getInstance('#userModal').hide();
                } else {
                    alert('保存失败');
                }
            } catch (error) {
                alert('请求失败');
            }
        }

        // 删除用户
        async function deleteUser(userId) {
            if (!confirm('确定要删除吗？')) return;

            try {
                const response = await fetch(`/api/users/${userId}`, {
                    method: 'DELETE'
                });

                if (response.ok) {
                    loadUsers();
                } else {
                    alert('删除失败');
                }
            } catch (error) {
                alert('请求失败');
            }
        }
    </script>
</body>
</html>